IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'up_Report_DistributionInspectionProjectSummary')
	BEGIN
		DROP  Procedure  up_Report_DistributionInspectionProjectSummary
	END

GO

CREATE Procedure up_Report_DistributionInspectionProjectSummary
	@ProjectId int = null
AS

DECLARE @totalOfCompleted int
DECLARE @totalOfEstimated int

--HANDLE OLD VERSION
IF (@ProjectId IS NULL)
BEGIN
	SELECT  @ProjectId = CONVERT(INT, SettingValue) FROM tb_Settings
	WHERE SettingKey like 'DistributionInspectionProjectId'
END

--Get total completed poles
SELECT 
	@totalOfCompleted = count(*) 
FROM 
	dbo.tb_Vendor_Distribution_Poles P
	INNER JOIN  dbo.tb_Vendor_Distribution_InspectionResults R 
		ON R.Vendor_Distribution_PoleFk = P.Vendor_Distribution_Poles_PoleId
WHERE
	P.ProjectFk = @ProjectId
	AND P.DistributionType = 1 --Inspection

--Get Estimated Counts
declare @EstimatedPartial money
declare @EstimatedVisual money

SELECT 
	@EstimatedPartial = EstimatedPartialCount
	,@EstimatedVisual = EstimatedVisualCount
FROM	
	tb_vendor_projects
WHERE 
	Vendor_ProjectId = @ProjectId

--Calcs total of estimated
SELECT	@totalOfEstimated = (@EstimatedVisual + @EstimatedPartial) 

/*
SELECT	
	@totalOfEstimated = (EstimatedVisual + EstimatedPartial) 
FROM
	uv_TotalDistributionEstimatedAssetsByInspectionType
*/

--PRINT @totalOfEstimated
--PRINT @totalOfCompleted

SELECT
	VP.*,
	CASE 
		WHEN VP.ActualEndDate IS NULL THEN dbo.fn_EstimateCompletionDate(@totalOfEstimated, @totalOfCompleted, VP.ActualStartDate) 
		ELSE VP.ActualEndDate 
	END	AS estimateCompletionDate
FROM 
	tb_Vendor_Projects VP 
WHERE 
	VP.Vendor_ProjectId = @ProjectId





GO

GRANT EXEC ON up_Report_DistributionInspectionProjectSummary TO PPIReports

GO

